package com.stt.base.service;

import com.stt.base.model.Device;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 设备服务类
 */
@Service
public class DeviceService {
    
    // 模拟设备数据存储
    private final Map<Long, Device> deviceMap = new ConcurrentHashMap<>();
    
    /**
     * 初始化一些测试设备
     */
    public DeviceService() {
        // 添加测试设备
        Device light = new Device();
        light.setId(1L);
        light.setName("客厅灯");
        light.setType("LIGHT");
        light.setStatus(false);
        light.setParameter(0);
        deviceMap.put(light.getId(), light);
        
        Device ac = new Device();
        ac.setId(2L);
        ac.setName("卧室空调");
        ac.setType("AC");
        ac.setStatus(false);
        ac.setParameter(26);
        deviceMap.put(ac.getId(), ac);
        
        Device curtain = new Device();
        curtain.setId(3L);
        curtain.setName("客厅窗帘");
        curtain.setType("CURTAIN");
        curtain.setStatus(false);
        curtain.setParameter(0);
        deviceMap.put(curtain.getId(), curtain);
    }
    
    /**
     * 获取所有设备
     */
    public List<Device> getAllDevices() {
        return new ArrayList<>(deviceMap.values());
    }
    
    /**
     * 获取单个设备
     */
    public Device getDevice(Long id) {
        return deviceMap.get(id);
    }
    
    /**
     * 控制设备开关
     */
    public void controlDeviceStatus(Long id, boolean status) {
        Device device = deviceMap.get(id);
        if (device != null) {
            device.setStatus(status);
            System.out.println("设备 " + device.getName() + " 已" + (status ? "开启" : "关闭"));
        }
    }
    /**
     * 根据设备名称查找设备
     * @param name 设备名称
     * @return 找到的设备，如果未找到返回null
     */
    public Device getDeviceByName(String name) {
        return deviceMap.values().stream()
                .filter(device -> device.getName().equals(name))
                .findFirst()
                .orElse(null);
    }
    /**
     * 控制设备参数
     */
    public void controlDeviceParameter(Long id, Integer parameter) {
        Device device = deviceMap.get(id);
        if (device != null) {
            // 参数范围验证
            switch (device.getType()) {
                case "LIGHT":
                case "CURTAIN":
                    if (parameter < 0 || parameter > 100) {
                        throw new IllegalArgumentException("参数范围应为0-100");
                    }
                    break;
                case "AC":
                    if (parameter < 16 || parameter > 30) {
                        throw new IllegalArgumentException("温度范围应为16-30℃");
                    }
                    break;
            }
            
            device.setParameter(parameter);
            System.out.println("设备 " + device.getName() + " 参数已设置为 " + parameter);
        }
    }
} 